const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  // 配置MCP代理
  app.use(
    '/api/mcp',
    createProxyMiddleware({
      target: 'http://localhost:3333',
      changeOrigin: true,
      // 简化路径重写规则
      pathRewrite: function(path) {
        // 移除/api/mcp前缀，确保正确传递到MCP服务
        console.log('原始路径:', path);
        const newPath = path.replace(/^\/api\/mcp\/amap_maps_maps/, '/amap/maps');
        console.log('重写路径:', newPath);
        return newPath;
      },
      onProxyReq: (proxyReq, req, res) => {
        // 记录代理请求的详细信息
        console.log('代理请求:', {
          method: req.method,
          originalUrl: req.originalUrl,
          targetUrl: proxyReq.path
        });
      },
      onError: (err, req, res) => {
        console.error('代理请求出错:', err);
        res.writeHead(500, {
          'Content-Type': 'application/json'
        });
        res.end(JSON.stringify({ 
          status: 'error', 
          message: '高德地图服务暂时不可用，请检查MCP服务是否正常运行',
          error: err.message
        }));
      },
      logLevel: 'debug'
    })
  );
}; 